# -*- coding: utf-8 -*-
"""
@Time    : 2021/3/23 9:49
@Author  : hui lin
"""
from __future__ import annotations
import random
from typing import Optional, TYPE_CHECKING

from client.model.entity_manager import entity_mgr
from client.model.gate_data import GateData
from client.model.skill.skill import Skill
from package.posi import Position
from package.static.const import MoveDirection, Faction, TypeIdConst
from client.model.tank.tank_base import TankBase
from package.universe import universe

if TYPE_CHECKING:
    from client.model.weapon.bullet import Bullet


def get_random_position() -> Position:
    x = random.randint(0, GateData().config.width)
    y = random.randint(1, GateData().config.height-1)
    return Position(x, y)


class NpcTank(TankBase):

    def __init__(self, type_id: TypeIdConst, **kwargs):
        super(NpcTank, self).__init__(type_id, faction=Faction.NPC, **kwargs)
        self.skill_reward: Optional[TypeIdConst] = None
        if "gate_id" in kwargs and "cur_wave" in kwargs and \
                self.static_info.tech_level >= 2:
            skill_pool = universe.get_gate_info(
                kwargs["gate_id"]).npc[kwargs["cur_wave"]].skill
            self.skill_reward = random.choice(skill_pool)

    def act_ai(self):
        # 当前停止时，下一帧行动ai:
        # 0.75的概率随机选择一个和当前不同的方向移动；0.25的概率开枪；
        if not self.is_dead and not self.real_speed:
            p = random.randint(0, 100)
            if 50 > p:
                return
            else:
                temps = MoveDirection.all_types()
                temps.remove(self.direction)
                new_direction = random.choice(temps)
                if MoveDirection.NONE == new_direction:
                    # 随机到不动时，代表开枪
                    bullet: Optional[Bullet] = self.shoot()
                    if bullet:
                        entity_mgr.npc_bullets.add(bullet)
                else:
                    self.set_move([new_direction])
        else:
            # 移动过程中，小概率(暂定为0.5%， 每帧判定1次，平均约3.3s开枪1次)会开枪
            p = random.randint(0, 10000)
            if p < 50:
                bullet: Optional[Bullet] = self.shoot()
                if bullet:
                    entity_mgr.npc_bullets.add(bullet)
            elif p < 75:
                # 小概率改变方向
                temps = MoveDirection.all_types()
                temps.remove(self.direction)
                temps.remove(MoveDirection.NONE)
                new_direction = random.choice(temps)
                self.set_move([new_direction])

    def can_remove(self) -> bool:
        if self.is_dead:
            self.image = self.dead_image
            if self.skill_reward:
                skill = Skill(self.skill_reward)
                skill.init_position(get_random_position())
                entity_mgr.skills.add(skill)
                self.skill_reward = None
        return self.need_remove
